package org.telemoney;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Servlet implementation class UnifiedCallBackServlet
 */
public class UnifiedCallBackServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UnifiedCallBackServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("====================Call Back From Common Pay=========================== ");
		Enumeration<String> attributes = request.getAttributeNames();
		while(attributes.hasMoreElements()){
			String key = attributes.nextElement();
			System.out.println(key + "-----" + request.getAttribute(key));
		}
		
		System.out.println("-----headers-----");
		Enumeration<String> headerNames = request.getHeaderNames();
		while(headerNames.hasMoreElements()){
			String key = headerNames.nextElement();
			System.out.println(key + "-----" + request.getHeader(key));
		}
		
		System.out.println("-----request-----");
		Map<String,String[]> map = request.getParameterMap();
		for(Map.Entry<String, String[]> entry : map.entrySet()){
			System.out.println(entry.getKey() + "----" + Arrays.asList(entry.getValue()).stream().collect(Collectors.joining(" | ")));
		}
		String commonPayJson = request.getParameter("commonpaydata");
		ObjectMapper objectMapper = new ObjectMapper();
		
		Map<String, Object> result = objectMapper.readValue(commonPayJson, new TypeReference<Map<String,Object>>(){});
		System.out.println(result.get("mid"));
		System.out.println(result.get("refid"));
		response.getWriter().write("mid=" + result.get("mid") + "&refid=" + result.get("refid"));
		System.out.println("====================Call Back From Common Pay End=========================== ");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
